<?php


namespace app\admin\controller;

use app\admin\validate\IDMustBePositiveInt;
use app\admin\validate\CouponValidate;
use app\service\model\CouponModel;
use app\service\Y;
use think\Request;

class Coupon extends BaseAdmin
{

    /**
     * 优惠券列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(Request $request): \think\response\Json
    {
        $data = CouponModel::paginate([
            'list_rows'=> input('param.limit', 10),
            'query' => input('param.')
        ])->toArray();
        return Y::table($data['data'], $data['total']);
    }

    /**
     * 创建、编辑优惠券
     * @param Request $request
     * @param CouponValidate $coupon_validate
     * @return \think\response\Json
     * @throws \app\service\exception\ParameterException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(Request $request, CouponValidate $coupon_validate): \think\response\Json
    {
        $id = input('param.id', 0);

        if ($request->isPost()) {
            $coupon_validate->goCheck();
            $param = $coupon_validate->getDataByRule();

            if (!$param['is_permanent_validity']) {
                // 不是永久有效，则检查有效期
                $validate = \think\facade\Validate::rule([
                        'start_time'  => 'require|dateFormat:Y-m-d H:i:s',
                        'end_time' => 'require|dateFormat:Y-m-d H:i:s|>:start_time'
                    ]);
                $param['start_time'] = input('param.start_time', '');
                $param['end_time'] = input('param.end_time', '');

                if (!$validate->check($param)) {
                    return Y::error($validate->getError());
                }
            }
            return CouponModel::saveData($param, $id);
        }

        $data = [];
        if ($id > 0) {
            $data = CouponModel::find($id);
        }
        return Y::success($data, '优惠券数据');
    }

    /**
     * 删除数据
     * @param IDMustBePositiveInt $IDMustBePositiveInt
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(IDMustBePositiveInt $IDMustBePositiveInt): \think\response\Json
    {
        $IDMustBePositiveInt->goCheck();
        $id = input('param.id');
        return $this->deleteDate((new CouponModel()), $id);
    }
}